package com.tpay.server.util;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.junit.internal.runners.model.MultipleFailureException;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unitils.core.TestListener;

public class RunAfter extends Statement {
	private static final Logger logger = LoggerFactory.getLogger(RunAfter.class);
	
	private final Statement junitStatement;
	private final Object testObject;
	private final Method testMethod;
	private final TestListener unitilsListener;
	
	public RunAfter(Statement junitStatement, Object testObject, Method testMethod, TestListener unitilsListener) {
		this.junitStatement = junitStatement;
		this.testObject = testObject;
		this.testMethod = testMethod;
		this.unitilsListener = unitilsListener;
	}

	@Override
	public void evaluate() throws Throwable {
		List<Throwable> errors = new ArrayList<Throwable>();

		try {
			logger.debug("@After 실행 전");
			this.junitStatement.evaluate();	// @After 실행
			logger.debug("@After 실행 후");
		} catch(Throwable e) {
			errors.add(e);
		}
		
		try {
			logger.debug("unitilsListener.afterTestTearDown 실행");
			this.unitilsListener.afterTestTearDown(testObject, testMethod);
		} catch(Throwable e) {
			errors.add(e);
		}
		
		if(errors.isEmpty())
			return;

		if(errors.size() == 1)
			throw errors.get(0);
		
		throw new MultipleFailureException(errors);
	}
}
